package com.btpj.module_login.ui

import androidx.lifecycle.Observer
import com.btpj.jetpack.base.BaseActivity
import com.btpj.jetpack.utils.ToastUtil
import com.btpj.module_login.R
import com.btpj.module_login.data.entity.LoginLayoutEntity
import com.btpj.module_login.databinding.ActivityLoginBinding
import com.btpj.module_login.utils.UserManager
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity<LoginViewModel, ActivityLoginBinding>() {

    private val mLoginLayoutEntity by lazy { LoginLayoutEntity() }

    override fun getLayoutId() = R.layout.activity_login

    override fun initView() {
        mBinding.bean = mLoginLayoutEntity

        iv_close.setOnClickListener { finish() }
        tv_featureName.setOnClickListener {
            mLoginLayoutEntity.isLogin = !mLoginLayoutEntity.isLogin
            resetEditText()
        }

        btn_login.setOnClickListener {
            val userName = et_userName.text.toString().trim()
            if (userName.isEmpty()) {
                ToastUtil.showShort("请输入用户名")
                return@setOnClickListener
            }

            val password = et_password.text.toString().trim()
            if (password.isEmpty()) {
                ToastUtil.showShort("密码")
                return@setOnClickListener
            }

            val surePassword = et_password.text.toString().trim()
            if (surePassword.isEmpty()) {
                ToastUtil.showShort("请输入确认密码")
                return@setOnClickListener
            }
            if (password != surePassword) {
                ToastUtil.showShort("确认密码与密码不一致")
                return@setOnClickListener
            }

            if (mLoginLayoutEntity.isLogin) {
                mViewModel.login(userName, password)
            } else {
                mViewModel.register(userName, password, surePassword)
            }
        }
    }

    private fun resetEditText() {
        et_userName.setText("")
        et_password.setText("")
        et_surePassword.setText("")
    }

    override fun createObserve() {
        super.createObserve()
        mViewModel.loginLiveData.observe(this, Observer {
            UserManager.saveUser(it)
            finish()
        })
    }
}